package logic

import (
	"context"
	"fmt"
	"strconv"
	"taobao/api/pkg"
	"taobao/goods_srv/user"

	"taobao/api/internal/svc"
	"taobao/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 账号密码登录

	//先查询用户信息
	info, err := l.svcCtx.UserSrv.FindUsernameInfo(l.ctx, &user.UserNameInfoRequest{Username: req.Username})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "查询用户信息失败",
			Data: nil,
		}, err
	}
	fmt.Print("%11111..............", info.UserId)
	fmt.Print("$22222..............", info.Password)

	if info.Password != req.Password {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "用户名或密码错误",
			Data: nil,
		}, err
	}
	log, err := l.svcCtx.UserSrv.UserLog(l.ctx, &user.UserLoginRequest{
		Username: req.Username,
		Password: req.Password,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "登录失败",
			Data: nil,
		}, err
	}

	token, err := pkg.GetJwtToken(strconv.FormatInt(log.UserId, 10))
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -2,
			Mag:  "token生成失败",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Cre: 0,
		Mag: "登录成功",
		Data: map[string]interface{}{
			"token": token,
		},
	}, err
}
